package com.tledu.student_manager.service;

import com.tledu.student_manager.dao.UserDao;
import com.tledu.student_manager.exception.CustomException;
import com.tledu.student_manager.model.User;

import java.util.List;

/**
 * @author cyrus
 */
public class UserService {
    private final UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User login(String username, String password) throws CustomException {
        // 实现登录的逻辑
        User user = userDao.getByUsername(username);
        if (user == null) {
            throw new CustomException("当前用户不存在");
        }
        // 用户存在
        if (!user.getPassword().equals(password)) {
            throw new CustomException("密码错误");
        }
        // 登录成功
        return user;
    }

    public List<User> list() throws CustomException {
        return userDao.list();
    }

    public void delete(int id) throws CustomException {
        userDao.delete(id);
    }

    public void add(User user) throws CustomException {
        User oldUser = userDao.getByUsername(user.getUsername());
        if (oldUser != null) {
            // 用户名已经存在了
            throw new CustomException("用户名存在");
        }
        userDao.add(user);
    }
}
